using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Barebones.Components;
using Barebones.Dependencies;
using Meat.Rendering;
using Microsoft.Xna.Framework.Graphics;
using Meat.Resources;

namespace Meat.Animation
{
    public class TextureAnimator : EntityComponent, Barebones.Framework.IUpdateable
    {
        Handle<VertexBufferResource<VertexPositionNormalTexture>> m_Buffer;

        readonly int m_FrameCount;
        int m_Fps;

        int m_CurrentFrame;
        float m_Elapsed;

        public bool Paused
        { get; set; }

        public TextureAnimator(int framecount, int fps)
        {
            m_FrameCount = framecount;
            m_Fps = fps;
        }

        public override IEnumerable<Barebones.Dependencies.IDependency> GetDependencies()
        {
            yield return new Dependency<Handle<VertexBufferResource<VertexPositionNormalTexture>>>(item => m_Buffer = item, item => m_Buffer = null);
        }

        public void Update(float dt)
        {
            if (Paused)
                return;

            m_Elapsed += m_Fps * dt;

            int increment = (int)Math.Floor(m_Elapsed);
            if (increment == 0)
                return;

            m_Elapsed -= increment;

            m_CurrentFrame = (m_CurrentFrame + increment) % m_FrameCount;

            var vertices = m_Buffer.Get();
            vertices.StartIndex = m_CurrentFrame * vertices.PrimitiveCount * 3;
        }
    }
}
